package com.makeunion.gdlbsdemo.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MultiPointItem;
import com.amap.api.maps.model.MultiPointOverlay;
import com.amap.api.maps.model.MultiPointOverlayOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.amap.api.services.routepoisearch.RoutePOIItem;
import com.amap.api.services.routepoisearch.RoutePOISearch;
import com.amap.api.services.routepoisearch.RoutePOISearchQuery;
import com.amap.api.services.routepoisearch.RoutePOISearchResult;
import com.makeunion.gdlbsdemo.R;
import com.makeunion.gdlbsdemo.overlay.DrivingRouteOverlay;

import java.util.ArrayList;
import java.util.List;

/**
 * 类说明
 *
 * @author renjialiang
 * @version [版本]
 * @see [相关类]
 * @since [模块]
 */
public class PoiRouteSearchActivity extends AppCompatActivity implements
        RoutePOISearch.OnRoutePOISearchListener {

    private MapView mapView;

    private AMap aMap;

    private Button tab1;

    private Button tab2;

    private Button tab3;

    private RouteSearch mRouteSearch;

    private RoutePOISearch routePOISearch;

    private LatLonPoint mStartPoint = new LatLonPoint(39.742295, 116.235891);
    private LatLonPoint mEndPoint = new LatLonPoint(39.995576, 116.481288);

    private MultiPointOverlay multiPointOverlay;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_poi_route_search);

        tab1 = (Button)findViewById(R.id.tab_1);
        tab2 = (Button)findViewById(R.id.tab_2);
        tab3 = (Button)findViewById(R.id.tab_3);
        mapView = (MapView) findViewById(R.id.map_view);
        mapView.onCreate(savedInstanceState); //此方法必须重写
        init();
    }

    private void init() {
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        addMarkers();
        searchRoute();
    }

    private void addMarkers() {
        LatLng start = new LatLng(mStartPoint.getLatitude(), mStartPoint.getLongitude());
        aMap.addMarker(new MarkerOptions()
                .position(start)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.start)));
        LatLng end = new LatLng(mEndPoint.getLatitude(), mEndPoint.getLongitude());
        aMap.addMarker(new MarkerOptions()
                .position(end)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.end)));
    }

    private void searchRoute() {
        mRouteSearch = new RouteSearch(this);
        mRouteSearch.setRouteSearchListener(new RouteSearch.OnRouteSearchListener() {
            @Override
            public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

            }

            @Override
            public void onDriveRouteSearched(DriveRouteResult result, int errorCode) {
                aMap.clear();// 清理地图上的所有覆盖物
                if (errorCode == AMapException.CODE_AMAP_SUCCESS) {
                    if (result != null && result.getPaths() != null) {
                        if (result.getPaths().size() > 0) {
                            final DrivePath drivePath = result.getPaths().get(0);
                            DrivingRouteOverlay drivingRouteOverlay = new DrivingRouteOverlay(
                                    PoiRouteSearchActivity.this, aMap, drivePath,
                                    result.getStartPos(),
                                    result.getTargetPos(), null);
                            drivingRouteOverlay.setNodeIconVisibility(false);//设置节点marker是否显示
                            drivingRouteOverlay.removeFromMap();
                            drivingRouteOverlay.addToMap();
                            drivingRouteOverlay.zoomToSpan();
                        } else {
                            Toast.makeText(PoiRouteSearchActivity.this, "对不起，没有搜索到相关数据",
                                    Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(PoiRouteSearchActivity.this, "对不起，没有搜索到相关数据",
                                Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(PoiRouteSearchActivity.this, "onDriveRouteSearched error.[" + errorCode + "]",
                            Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

            }

            @Override
            public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {

            }
        });

        final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
                mStartPoint, mEndPoint);
        RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(
                fromAndTo, //路径规划的起点和终点
                RouteSearch.DrivingDefault, //驾车模式
                null, //途经点
                null, //示避让区域
                null //避让道路
        );
        mRouteSearch.calculateDriveRouteAsyn(query);
    }

    public void onTab1Click(View view) {
        tab1.setTextColor(Color.BLUE);
        tab2.setTextColor(Color.LTGRAY);
        tab3.setTextColor(Color.LTGRAY);
        searchRoutePOI(RouteSearch.DrivingDefault, RoutePOISearch.RoutePOISearchType.TypeGasStation);
    }

    public void onTab2Click(View view) {
        tab1.setTextColor(Color.LTGRAY);
        tab2.setTextColor(Color.BLUE);
        tab3.setTextColor(Color.LTGRAY);
        searchRoutePOI(RouteSearch.DrivingDefault, RoutePOISearch.RoutePOISearchType.TypeATM);
    }

    public void onTab3Click(View view) {
        tab1.setTextColor(Color.LTGRAY);
        tab2.setTextColor(Color.LTGRAY);
        tab3.setTextColor(Color.BLUE);
        searchRoutePOI(RouteSearch.DrivingDefault, RoutePOISearch.RoutePOISearchType.TypeToilet);
    }

    private void searchRoutePOI(int mode, RoutePOISearch.RoutePOISearchType type) {
        RoutePOISearchQuery query = new RoutePOISearchQuery(mStartPoint ,mEndPoint, mode, type, 250);
        routePOISearch = new RoutePOISearch(this, query);
        routePOISearch.setPoiSearchListener(this);
        routePOISearch.searchRoutePOIAsyn();
    }

    @Override
    public void onRoutePoiSearched(RoutePOISearchResult routePOISearchResult, int rCode) {
        if (routePOISearchResult == null) {
            return;
        }
        List<RoutePOIItem> routePoiItems = routePOISearchResult.getRoutePois();
        if (routePoiItems == null) {
            return;
        }
        List<MultiPointItem> list = new ArrayList<>();
        for (RoutePOIItem item : routePoiItems) {
            LatLonPoint point = item.getPoint();
            list.add(new MultiPointItem(new LatLng(point.getLatitude(), point.getLongitude())));
        }
        showResultOnMap(list, routePOISearchResult.getQuery().getSearchType());
    }

    private void showResultOnMap(List<MultiPointItem> list, RoutePOISearch.RoutePOISearchType type) {
        if (multiPointOverlay != null) {
            multiPointOverlay.remove();
        }
        MultiPointOverlayOptions overlayOptions = new MultiPointOverlayOptions();
        if (type == RoutePOISearch.RoutePOISearchType.TypeGasStation) {
            overlayOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_oil));
        } else if (type == RoutePOISearch.RoutePOISearchType.TypeATM) {
            overlayOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_atm));
        } else if (type == RoutePOISearch.RoutePOISearchType.TypeToilet) {
            overlayOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_wc));
        } else {
            overlayOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_blue));
        }
        overlayOptions.anchor(0.5f, 0.5f);

        multiPointOverlay = aMap.addMultiPointOverlay(overlayOptions);
        multiPointOverlay.setItems(list);

        AMap.OnMultiPointClickListener multiPointClickListener = new AMap.OnMultiPointClickListener() {
            @Override
            public boolean onPointClick(MultiPointItem pointItem) {
                Log.e("TAG", "pointItem=" + pointItem.getLatLng());
                Toast.makeText(PoiRouteSearchActivity.this, "pointItem=" + pointItem.getLatLng(), Toast.LENGTH_SHORT).show();
                return false;
            }
        };
        aMap.setOnMultiPointClickListener(multiPointClickListener);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }
}
